package edu.gduf.controller;

import edu.gduf.domain.Associations;
import edu.gduf.domain.RegAssociation;
import edu.gduf.domain.ResultInfo;
import edu.gduf.domain.User;
import edu.gduf.service.UserService;
import edu.gduf.utils.JwxtUtil;
import edu.gduf.utils.UserUtil;
import org.apache.ibatis.annotations.Param;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.net.URISyntaxException;

@Controller
@SessionAttributes(value = {"uid","username","nickname","type","photo"},types = {Integer.class,String.class,String.class,Integer.class,
String.class})
public class LoginController {

    @Autowired
    private UserService userService;
    @Autowired
    private JwxtUtil jwxtUtil;

    /**
     * 跳转到用户登陆的页面
     * @return
     */
    @RequestMapping(value = "/login",method = RequestMethod.GET)
    public String login(){
        return "login";
    }

    /**
     * 跳转到用户注册的页面
     * @return
     */
    @RequestMapping(value = "/register",method = RequestMethod.GET)
    public String register(){
        return "register";
    }

    /**
     * 退出登陆
     * @return
     */
    @RequestMapping(value = "/logout",method = RequestMethod.GET)
    public String loginout(){
        return "redirect:login";
    }

    /**
     * 用于验证用户登陆的表单
     * @param user
     * @param model
     * @return
     */
    @RequestMapping(value = "/login",method = RequestMethod.POST)
    public String login(User user, Model model){
       if(user.getUsername() != null && user.getPassword() != null){
           // 初始化
           Subject subject = SecurityUtils.getSubject();
           // 将登陆表单封装成token对象
           UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername(),user.getPassword());
           String msg = "";
           try{
               //登录，即身份校验，由通过Spring注入的UserRealm会自动校验输入的用户名和密码在数据库中是否有对应的值
               subject.login(token);
               // 获取用户的个人信息
               User loginuser = userService.findUserByUserName(user.getUsername());
               // 将一些用户数据存入到session中
               model.addAttribute("uid",loginuser.getUid());
               model.addAttribute("username",loginuser.getUsername());
               model.addAttribute("nickname",loginuser.getNickname());
               model.addAttribute("type",loginuser.getType());
               model.addAttribute("photo",loginuser.getPhoto());
               return "redirect:/user/update";
           }catch (UnknownAccountException e){
               e.printStackTrace();
               msg = "用户不存在";
           }catch (IncorrectCredentialsException e){
               e.printStackTrace();
               msg = "账号或密码错误";
           }catch (DisabledAccountException e) {
               e.printStackTrace();
               msg = "用户暂时不可用";
           }catch (AuthenticationException e){
               e.printStackTrace();
               msg = "账号未知错误";
           }finally {
               if(msg != ""){
                   model.addAttribute("loginmsg",msg);
                   return "login";
               }
           }
       }
       return "login";
    }


    /**
     * 用于ajax的表单验证
     * @param user
     * @return
     */
    @RequestMapping(value = "/checkusername",method = RequestMethod.POST)
    @ResponseBody
    public ResultInfo check(@RequestBody User user){
        if(user.getUsername() == null || user.getUsername().equals(""))
            return ResultInfo.failInfo("用户名不能为空");
        else if(userService.checkUserName(user.getUsername())!=null)
            return ResultInfo.failInfo("该用户名已存在");
        else if(user.getNumber() == null || user.getNumber().equals(""))
            return ResultInfo.failInfo("学号不能为空");
        else if(userService.checkXh(user.getNumber())!=null)
            return ResultInfo.failInfo("学号已存在");
        else
            return ResultInfo.successInfo("还行");
    }

    /**
     * 返回该用户类型注册的页面
     * @param type
     * @return
     */
    @RequestMapping(value = "/register/type={type}",method = RequestMethod.GET)
    public String register(@PathVariable(value = "type") Integer type){
        if(type == 1){
            // 如果用户注册类型为普通用户，则返回普通用户注册页面
            return "userregister";
        }else //
            // 如果用户注册类型为组织,则返回组织注册的页面
            return "associationregister";
    }


    /**
     * 处理用户注册表单
     * @param user
     * @return
     * @throws URISyntaxException
     */
    @RequestMapping(value = "/register/type=1",method = RequestMethod.POST)
    @ResponseBody
    public ResultInfo userregister(@RequestBody User user) throws URISyntaxException {
        System.out.println(user);
        // 1. 基本判断逻辑
        if(user.getUsername() == null)
            return ResultInfo.failInfo("用户名不可以为空");
        else if (user.getUsername().length() < 6)
            return ResultInfo.failInfo("用户名不能小于6位");
         else if(userService.checkUserName(user.getUsername()) != null)
            return ResultInfo.failInfo("该用户名已经存在");
        else if (UserUtil.checkUsername(user.getUsername()))
            return ResultInfo.failInfo("用户名不能存在特殊符号");
        else if(userService.checkXh(user.getNumber()) != null)
            return ResultInfo.failInfo("该学号已经存在");
        else if(user.getPassword().length() < 6)
            return ResultInfo.failInfo("密码不能小于6位");
        else if(user.getNickname() == null)
            return ResultInfo.failInfo("昵称不能为空");
        else if (user.getNickname().length() < 2)
            return ResultInfo.failInfo("昵称不能小于2位");
        // 验证学号和教务系统密码是否正确
        User reguser = userService.getStudentInfo(user.getNumber(), user.getJwxtpassword());
        if(reguser == null)
            return ResultInfo.failInfo("学号和认证密码错误");
        else{
            reguser.setUsername(user.getUsername());
            // 使用md5加密后存入数据库中
            reguser.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes()));
            reguser.setNickname(user.getNickname());
            reguser.setType(1);
            reguser.setPhoto("/upload/images/logo3.png");
            reguser.setIs_lock(0);
            reguser.setLikes(0);
            return userService.register(reguser);
        }
    }


    /**
     * 组织注册提交的表单
     * @param regAssociation
     * @return
     */
    @RequestMapping(value = "/register/type=2",method = RequestMethod.POST)
    @ResponseBody
    public ResultInfo associationregister(@RequestBody RegAssociation regAssociation){
        System.out.println(regAssociation);
        // 1. 基本判断逻辑
        if(regAssociation.getUsername() == null)
            return ResultInfo.failInfo("用户名不可以为空");
        else if (regAssociation.getUsername().length() < 6)
            return ResultInfo.failInfo("用户名不能小于6位");
        else if(userService.checkUserName(regAssociation.getUsername()) != null)
            return ResultInfo.failInfo("该用户名已经存在");
        else if (UserUtil.checkUsername(regAssociation.getUsername()) == true)
            return ResultInfo.failInfo("用户名不能存在特殊符号");
        else if(regAssociation.getPassword() == null)
            return ResultInfo.failInfo("密码不能为空");
        else if(regAssociation.getPassword().length() < 6)
            return ResultInfo.failInfo("密码不能小于6位");
        else if(regAssociation.getNickname()  == null)
            return ResultInfo.failInfo("昵称不能为空");
        else if (regAssociation.getNickname().length() < 2)
            return ResultInfo.failInfo("昵称不能小于2位");
        else if(regAssociation.getIdentify_name() == null || regAssociation.getIdentify_name() == "")
            return ResultInfo.failInfo("认证名不能为空");
        else if(regAssociation.getIdentify_type() != 1 && regAssociation.getIdentify_type() != 2 && regAssociation.getIdentify_type() != 3)
            return ResultInfo.failInfo("认证类型错误");
        else if(regAssociation.getDescription() == null)
            return ResultInfo.failInfo("请输入描述");
        User reguser = new User();
        reguser.setUsername(regAssociation.getUsername());
        reguser.setPassword(DigestUtils.md5DigestAsHex(regAssociation.getPassword().getBytes()));
        reguser.setType(2);
        reguser.setLikes(0);
        Associations association = new Associations();
        association.setIdentify_type(regAssociation.getIdentify_type());
        association.setIdentify_name(regAssociation.getIdentify_name());
        reguser.setAssociation(association);
        reguser.setNickname(regAssociation.getNickname());
        reguser.setDescription(regAssociation.getDescription());
        reguser.setIs_lock(1);
        reguser.setPhoto("/upload/images/logo3.png");
        return userService.register(reguser);
    }



}
